package org.study.poi_excel.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ou_quan_sheng
 * Description:这个一个Excel公共工具类，默认使用excel2007版本
 */
public class CommonUtils {

	/**
	 * 判断是不是IE浏览器，该方法直接由setExcelFileDownHeader方法替代
	 * 
	 * @param request
	 * @return
	 */
	public static boolean isIE(HttpServletRequest request) {
		String header = request.getHeader("USER-AGENT").toLowerCase();
		return (header.indexOf("msid") > 0 || header.indexOf("rv:11.0") > 0 ||
				header.indexOf("edge") > 0 || header.indexOf("trident") > 0);
	}

	/**
	 * <pre>
	 * 浏览器下载文件时需要在服务端给出下载的文件名，当文件名是ASCII字符时没有问题 当文件名有非ASCII字符时就有可能出现乱码
	 *
	 * 这里的实现方式参考这篇文章
	 * http://blog.robotshell.org/2012/deal-with-http-header-encoding-for-file-download/
	 *
	 * 最终设置的response header是这样:
	 *
	 * Content-Disposition: attachment; filename="encoded_text";
	 * filename*=utf-8''encoded_text
	 *
	 * 其中encoded_text是经过RFC 3986的“百分号URL编码”规则处理过的文件名
	 * 设置excel文件下载头  
	 * @param response
	 * @param fileName
	 * 兼容火狐谷歌
	 */
	public static void setExcelFileDownHeader(HttpServletResponse response, String fileName,HttpServletRequest request) {
		String copy = fileName;
		if(!isIE(request)) {
			try {
				copy = new String(copy.getBytes("UTF-8"),"ISO-8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		setExcelFileDownHeader(response,copy);
	}
	/**
	 * IE浏览器下载
	 * @param response
	 * @param fileName
	 */
	public static void setExcelFileDownHeader(HttpServletResponse response, String fileName) {
		response.reset();
		String copy = encodeURIComponent(fileName+getNow()+Contants.DEFAULT_EXCEL_SUFFIX);
		String headerKey = "Content-Disposition";
		String herderValue = "attachment; filename=\"" + copy + "\"; filename*=utf-8' '" + copy;
		response.setHeader(headerKey, herderValue);
		setNocache(response);
		response.setContentType("application/vnd.ms-excel");
	}

	public static String encodeURIComponent(String value) {
		String result = "";
		try {
			result = URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 设置客户端不缓存
	 * @param response
	 */
	public static void setNocache(HttpServletResponse response) {
		response.addHeader("Pargam", "no-cache");
		response.addHeader("Cache-Control", "no-cache");
	}
	
	public static String getNow() {
		Date now = new Date();
		SimpleDateFormat fat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		return fat.format(now);
	}
}
